package com.qbccn.usercenter.service.impl;

import com.qbccn.usercenter.domain.UcUser;
import com.qbccn.usercenter.domain.UcUserRole;
import com.qbccn.usercenter.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author linke
 * @date 2020/5/23 18:31
 * @description
 */
@Component
public class CustomUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username)){
            throw new UsernameNotFoundException(null);
        }
        UcUser user=userService.getUser(username);
        if (user==null){
            throw new UsernameNotFoundException("账号不存在！");
        }
        if (user.getStatus()==0){
            throw new  RuntimeException("账号无效");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        List<UcUserRole> roles=userService.getRoles(user.getId());
        roles.forEach(r->{
            //security的验证规则需要ROLE_，由于我数据库是vip1、vip2、vip3这种值，需要加上ROLE_
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + r.getRoleCode()));
        });
        return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
    }
}
